package cn.ticsmyc.tools.resourcesLoader;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

/**
 * 用于加载 .properties 文件
 * @author Ticsmyc
 * @date 2020-12-21 17:30
 */
public class PropertiesLoader {

    /**
     * 【使用相对路径】
     * 加载classpath路径下的.properties文件
     * @param path 格式要求【 "log4j.properties" 或者 "log/log4j.properties" 】，不能以"/"开头
     * @return
     */
    public static Properties load(String path){
       InputStream resourceAsStream = null;
       Properties properties;
       try {
           resourceAsStream = PropertiesLoader.class.getClassLoader().getResourceAsStream(path);
           BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream));
           properties = new Properties();
           properties.load(bufferedReader);
        } catch (IOException e) {
           throw new RuntimeException(String.format("%s 资源载入失败", path), e);
        }finally{
           if(resourceAsStream!= null){
               try {
                   resourceAsStream.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       return properties;
    }
}
